# -*- coding:utf-8 -*-

import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime
import time
import re
import csv
from pymongo import MongoClient
import zlib


requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告


"""
爱奇艺-弹幕获取
弹幕每5分钟请求一次
1.获取aid。搜索avlistinfo  
"""


class Aiqiyi_Get():
    def __init__(self):
        #声明一个CookieJar对象实例来保存cookie
        # requests.utils.dict_from_cookiejar(html.cookies)  # 获取cookies转dict
        self.cookie = cookiejar.CookieJar()
        # ua = UserAgent(use_cache_server=False)  # 禁用服务器缓存
        self.headers = {
            # 'User-Agent': ua.random,
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"

        }

    # 通过aid获取视频列表
    def get_tv_id(self, aid):
        # tv_id列表
        tv_id_list = []

        for page in range(1, 3):
            url = f"https://pcw-api.iqiyi.com/albums/album/avlistinfo?aid={aid}&page={str(page)}&size=30"
            # 请求网页内容
            # res = requests.get(url).text
            res = HttpUtils.do_request("GET", url, self.headers, "").text

            res_json = json.loads(res)

            # 视频列表
            move_list = res_json['data']['epsodelist']
            for j in move_list:
                dict_data = dict()
                dict_data['tvId'] = j['tvId']  # tvid
                dict_data['name'] = j['name']  # 连续剧第几集
                dict_data['subtitle'] = j['subtitle']  # 简介
                dict_data['duration'] = j['duration']  # 视频时间
                tv_id_list.append(dict_data)

        return tv_id_list

    # 获取弹幕信息
    def get_bullet(self, item):
        tv_id = str(item['tvId'])
        duration = item['duration']
        # duration = int(str(duration).split(':')[0])
        if int(str(duration).split(':')[1]) == 0:
            duration = int(str(duration).split(':')[0])
            count = duration / 5
        else:
            duration = int(str(duration).split(':')[0])
            count = duration / 5 + 1
        for page in range(1, int(count) + 1):
            url = f"https://cmts.iqiyi.com/bullet/{tv_id[-4:-2]}/{tv_id[-2:]}/{tv_id}_300_{str(page)}.z"
            print(url)

            # 请求弹幕压缩文件
            res = HttpUtils.do_request("GET", url, self.headers, "").content
            res_byte = bytearray(res)
            xml = zlib.decompress(res_byte).decode('utf-8')
            root = etree.XML(xml.encode("utf-8"))

            for r in root.xpath('//bulletInfo'):
                dict_data = dict()
                dict_data['txt'] = r.xpath('./content/text()')[0]
                dict_data['uid'] = r.xpath('./userInfo/uid/text()')[0]
                dict_data['name'] = r.xpath('./userInfo/name/text()')[0]
                print(dict_data)


if __name__ == '__main__':
    aiqiyi_get = Aiqiyi_Get()

    # 节目id
    my_aid = '240617901'
    # tv_id列表
    my_tv_id_list = aiqiyi_get.get_tv_id(my_aid)
    for t in my_tv_id_list:
        aiqiyi_get.get_bullet(t)
